<template>
  <div class="order-page">
    <!-- 头部 -->
    <div class="page-header">
      <div class="header-content-fun">
        <!-- 日期选择器 -->
        <div class="header-dateSelect">
          <span class="dateSelect-tip">按日期筛选订单:</span>
          <el-date-picker v-model="pickerDate" type="daterange" range-separator="---" start-placeholder="起始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" size="default"/>
          <el-button type="primary" class="dateSelect-btn" @click="screen_btn">筛选</el-button>
        </div>
        <div class="header-select">
          <span class="select-tip" style="margin-right:10px;">订单排序:</span>
          <el-select v-model="orderSortSelect" placeholder="默认排序" style="width: 150px" @change="orderSortChange">
            <el-option  v-for="item in orderSortOptions" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </div>
        <div class="header-btns">
          <el-button type="success" :icon="Position" :disabled="selectedOrderList.length === 0" @click="batchUpdateOrderState_btn">批量发货</el-button>
          <el-button type="danger" :icon="Delete" :disabled="selectedOrderList.length === 0" @click="batchDeleteOrder_btn">批量删除订单</el-button>
        </div>
      </div>
      <div class="header-content-other">
        <div class="other-search">
          <el-input v-model="searchInput" placeholder="输入用户名或订单号搜索订单" style="width: 220px;"></el-input>
          <el-button type="primary" @click="searchOrder_btn">搜索</el-button>
        </div>
        <div class="other-select">
          <span class="select-tip" style="margin-right:10px;">订单状态筛选:</span>
          <el-select v-model="orderStateSelect" placeholder="筛选订单状态" style="width: 150px" @change="orderStateChange">
            <el-option  v-for="item in orderStateOptions" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </div>
      </div>
    </div>
    <!-- 订单信息表部分 -->
    <el-table :data="orderList" border style="width: 100%" @select-all="tableSelectChange" @select="tableSelectChange">
      <el-table-column type="selection" width="50" />
      <el-table-column type="index" label="序号" width="55" />
      <el-table-column prop="orderId" label="订单号" width="160"/>
      <el-table-column prop="username" label="下单用户" width="90"/>
      <el-table-column prop="commodityName" label="商品名称" width="100"/>
      <el-table-column prop="commodityStandardStr" label="商品规格" width="150"/>
      <el-table-column prop="commodityCount" label="商品数量" width="90"/>
      <el-table-column prop="orderTotalPrice" label="订单总价(￥)" width="110"/>
      <el-table-column prop="orderState" label="订单状态" width="90"/>
      <el-table-column prop="linkUser" label="订单联系人" width="100"/>
      <el-table-column prop="linkAddress" label="收货地址" width="150"/>
      <el-table-column prop="linkPhone" label="收货人电话" width="120"/>
      <el-table-column prop="logisticsInfo" label="物流信息" width="90"/>
      <el-table-column prop="orderRemark" label="订单备注" width="120"/>
      <el-table-column prop="updateTime" label="更新时间" width="120"/>
      <el-table-column prop="createTime" label="创建时间" width="120"/>
      <el-table-column label="操作" width="200" align="center">
        <template #="{row,$index}">          
          <el-popconfirm title="确定要发货吗?" @confirm="deliverGood_btn(row)">
            <template #reference>
              <el-button :disabled="!(row.orderState === '已支付' || row.orderState === '待发货')" type="primary" :icon="Position" title="去发货"></el-button>
            </template>
          </el-popconfirm>
          <el-button type="success" :icon="Edit" title="编辑订单" @click="editOrder_btn(row)"></el-button>       
          <el-popconfirm title="确定要删除该订单吗?" @confirm="deleteOrder_btn(row)">
            <template #reference>
              <el-button type="info" :icon="Delete" title="删除订单"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器部分 -->
    <el-pagination background layout="prev, pager, next, total, sizes, ->, jumper" :total="orderCount" :page-sizes="[3,5,10,20,30,50]" :default-current-page="pagination_page" :default-page-size="pagination_size" @change="pagination_change" class="page-pagination"/>
    <!-- drawer_dialog抽屉部分 -->
    <el-drawer ref="drawerRef" v-model="drawer_dialog" title="修改订单信息" :before-close="drawerDialogHandleClose" direction="rtl" class="drawerDialog">
      <div class="drawerDialog_content">
        <el-form :model="orderInfo_form" ref="userInfoForms">
          <el-form-item label="订单号:" label-width="100px">
            <span class="form-item-text">{{ orderInfo_form.orderId }}</span>
          </el-form-item>
          <el-form-item label="下单用户:" label-width="100px">
            <span class="form-item-text">{{ orderInfo_form.username }}</span>
          </el-form-item>
          <el-form-item label="商品名称:" label-width="100px">
            <span class="form-item-text">{{ orderInfo_form.commodityName }}</span>
          </el-form-item>
          <el-form-item label="规格描述:" label-width="100px">
            <span class="form-item-text">{{ orderInfo_form.commodityStandardStr }}</span>
          </el-form-item>
          <el-form-item label="商品数量:" label-width="100px">
            <span class="form-item-text">{{ orderInfo_form.commodityCount }}</span>
          </el-form-item>
          <el-form-item label="订单总价(￥):" label-width="100px">
            <span class="form-item-text">{{ orderInfo_form.orderTotalPrice }}</span>
          </el-form-item>
          <el-form-item label="订单状态:" label-width="100px">
            <el-select v-model="orderInfo_form.orderState" :placeholder="orderInfo_form.orderState" style="width: 150px">
              <el-option  v-for="item in orderStateOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="联系人:" label-width="100px">
            <el-input v-model="orderInfo_form.linkUser" autocomplete="off" />
          </el-form-item>
          <el-form-item label="联系人手机:" label-width="100px">
            <el-input v-model="orderInfo_form.linkPhone" autocomplete="off" />
          </el-form-item>
          <el-form-item label="联系人地址:" label-width="100px">
            <el-input v-model="orderInfo_form.linkAddress" autocomplete="off" />
          </el-form-item>
          <el-form-item label="物流信息:" label-width="100px">
            <textarea name="" id="" cols="10" rows="10" v-model="orderInfo_form.logisticsInfo" class="textarea logisticsInfo-textarea"></textarea>
          </el-form-item>
          <el-form-item label="订单备注:" label-width="100px">
            <textarea name="" id="" cols="10" rows="10" v-model="orderInfo_form.orderRemark" class="textarea orderRemark-textarea"></textarea>
          </el-form-item>
        </el-form>
        <div class="drawerDialog_btns">
          <el-button @click="drawerDialogCancel_btn">取消</el-button>
          <el-button type="primary" :loading="drawer_dialog_btn_loading" @click="drawerDialogSave_btn">修改</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted } from "vue";
//引入ElementPlus组件
import { ElTable, ElTableColumn, ElButton, ElPagination, ElDatePicker, ElSelect, ElOption, ElInput, ElMessage, ElDrawer, ElForm, ElFormItem, ElPopconfirm, ElMessageBox } from "element-plus";
import { Delete, Position, Edit } from '@element-plus/icons-vue';
//引入请求函数
import { reqOrderList, updateOrderInfo, reqDeleteOrder, reqOrderListByDate, reqOrderListSort, reqOrderListByState, reqOrderListByOrderIdOrUsername, reqBatchUpdateOrderState, reqBatchDeleteOrder } from "@/api/order/index.ts";

//订单列表数据
let orderList = ref([]);
let orderCount = ref(0);
//订单表格选择的数据
let selectedOrderList = ref([]);

//分页器相关数据
let pagination_page = ref(1);
let pagination_size = ref(3);

//drawer_dialog抽屉部分相关数据
let drawer_dialog = ref(false);
let drawer_dialog_btn_loading = ref(false);
const orderInfo_form = reactive({
  id:0,  //订单主键id
  orderId:"",  //订单号
  username:"",  //下单用户
  commodityName:"",  //商品名称
  commodityStandardStr:"",  //商品规格描述
  commodityCount:"",  //商品数量
  orderTotalPrice:"",  //订单总价
  orderState:"",  //订单状态
  linkUser:"",  //订单联系人
  linkPhone:"",  //订单联系人手机
  linkAddress:"",  //订单联系人地址
  logisticsInfo:"",  //订单物流信息
  orderRemark:"",  //订单备注
  createTime:"",  //订单创建时间
  updateTime:""  //订单更新时间
})

//订单排序select选择器
let orderSortSelect = ref("");
//订单状态select选择器
let orderStateSelect = ref("");
//日期picker组件
let pickerDate = ref([]);  //选择的日期
//搜索订单搜索框绑定数据
let searchInput = ref("");
//订单排序select选择器选项
const orderSortOptions = [{id:0,label:"下单时间升序"},{id:1,label:"下单时间降序"},{id:2,label:"订单更新时间升序"},{id:3,label:"订单更新时间降序"},{id:4,label:"订单总价升序"},{id:5,label:"订单总价降序"}];
//订单状态select选择器选项
const orderStateOptions = [{id:0,value:"待支付",label:"待支付"},{id:1,value:"已支付",label:"已支付"},{id:2,value:"待发货",label:"待发货"},{id:3,value:"已发货",label:"已发货"},{id:4,value:"运输中",label:"运输中"},{id:5,value:"已收货",label:"已收货"},{id:6,value:"已评价",label:"已评价"},{id:7,value:"已取消",label:"已取消"},{id:8,value:"已退货",label:"已退货"}];

//获取订单列表数据
const getOrderList = async (page:number = 1, pageSize:number = 3) => {
  let res = await reqOrderList(page, pageSize);
  if(res.code === 200) {
    orderList.value = res.data.rows;
    orderCount.value = res.data.total;
    ElMessage({type:"success",message:"订单列表数据获取成功!"});
  }
  console.log('分页获取订单列表数据api',res);
}
//分页器的page、pageSize的change事件
const pagination_change = (currentPage:number, pageSize:number) => {
  pagination_page.value = currentPage;
  pagination_size.value = pageSize;
  getOrderList(currentPage, pageSize);
}
//订单信息表中相关按钮事件
const editOrder_btn = (orderInfo:any) => {
  //打开drawer_dialog
  drawer_dialog.value = true;
  //给orderInfo_form赋值
  orderInfo_form.id = orderInfo.id;
  orderInfo_form.orderId = orderInfo.orderId;
  orderInfo_form.username = orderInfo.username;
  orderInfo_form.commodityName = orderInfo.commodityName;
  orderInfo_form.commodityStandardStr = orderInfo.commodityStandardStr;
  orderInfo_form.commodityCount = orderInfo.commodityCount;
  orderInfo_form.orderTotalPrice = orderInfo.orderTotalPrice;
  orderInfo_form.orderState = orderInfo.orderState;
  orderInfo_form.linkUser = orderInfo.linkUser;
  orderInfo_form.linkPhone = orderInfo.linkPhone;
  orderInfo_form.linkAddress = orderInfo.linkAddress;
  orderInfo_form.logisticsInfo = orderInfo.logisticsInfo;
  orderInfo_form.orderRemark = orderInfo.orderRemark;
  orderInfo_form.createTime = orderInfo.createTime;
  orderInfo_form.updateTime = orderInfo.updateTime;
}
const deliverGood_btn = async (orderInfo:any) => {
  //检查参数
  if(orderInfo.orderId === undefined || orderInfo.orderId === "" || orderInfo.orderState !== "已支付")return;
  const params = {orderId:"",orderState:"已发货"};
  params.orderId = orderInfo.orderId;
  //发请求
  let res = await updateOrderInfo(params);
  if(res.code === 200){
    ElMessage({type:"success",message:`订单${params.orderId}发货成功!`});
    //更新列表信息
    getOrderList(pagination_page.value, pagination_size.value);
  } else {
    ElMessage({type:"error",message:`订单${params.orderId}发货失败!`});
  }
  console.log('平台订单修改api',res);
}
const deleteOrder_btn = async (orderInfo:any) => {
  //检查参数
  if(orderInfo.orderId === undefined || orderInfo.orderId === "")return;
  //发请求
  let res = await reqDeleteOrder(orderInfo.orderId);
  if(res.code === 200){
    ElMessage({type:"success",message:`订单${orderInfo.orderId}删除成功!`});
    //更新列表信息
    getOrderList(pagination_page.value, pagination_size.value);
  } else {
    ElMessage({type:"error",message:`订单${orderInfo.orderId}删除失败!`});
  }
  console.log('平台订单删除api',res);
}

//根据日期筛选订单按钮事件
const screen_btn = async () => {
  let startDate:string = pickerDate.value[0];
  let endDate:string = pickerDate.value[1];
  if((startDate === null && startDate === "")||(endDate === null && endDate === "")) return ElMessage({type:"info",message:"请选择日期!"});
  //console.log(startDate, endDate);return;
  //调用接口发请求
  let res = await reqOrderListByDate(startDate, endDate);
  if(res.code === 200) {
    if(res.data.includes ("未查询到数据")) {
      ElMessage({type:"info",message:"未查询到数据!"});
    } else {
      ElMessage({type:"success",message:"订单筛选成功!"});
    }
    //更新订单列表信息
    orderList.value = res.data.rows;
    orderCount.value = res.data.total;
  } else {
    ElMessage({type:"error",message:"订单筛选失败!"})
  }
  console.log("根据日期筛选订单api",res);
}
//订单排序el-select的change事件
const orderSortChange = async (selectedItemId:number) => {
  let fieldName = "";
  let sortRule = "";
  switch (selectedItemId) {
    case 0:
      fieldName = "create_time";
      sortRule = "asc";
      break;
    case 1:
      fieldName = "create_time";
      sortRule = "desc";
      break;
    case 2:
      fieldName = "update_time";
      sortRule = "asc";
      break;
    case 3:
      fieldName = "update_time";
      sortRule = "desc";
      break;
    case 4:
      fieldName = "order_total_price";
      sortRule = "asc";
      break;
    case 5:
      fieldName = "order_total_price";
      sortRule = "desc";
      break;
    default:
      fieldName = "create_time";
      sortRule = "desc";
      break;
  }
  if(fieldName === "" || sortRule === "") return;
  //调用接口发送请求
  let res = await reqOrderListSort(fieldName,sortRule);
  if(res.code === 200) {
    //更新订单列表
    orderList.value = res.data.rows;
    orderCount.value = res.data.total;
    //信息提示
    ElMessage({type:"success",message:"订单排序成功!"});
  } else {
    ElMessage({type:"error",message:"订单请求排序失败!"});
  }
  console.log("订单创建、更新、总价排序api",res);
}
//订单筛选el-select的change事件
const orderStateChange = async (selectedItemId:number) => {
  let orderState = "";
  orderStateOptions.forEach(item => {
    if(item.id === selectedItemId){
      orderState = item.value;
    }
  })
  if(orderState === "") return;
  //发送请求
  let res = await reqOrderListByState(orderState);
  if(res.code === 200) {
    //更新订单列表
    orderList.value = res.data.rows || [];
    orderCount.value = res.data.total || 0;
    //信息提示
    ElMessage({type:"success",message:"筛选订单状态成功!"});
  } else {
    ElMessage({type:"error",message:"筛选订单状态失败!"});
  }
  console.log("订单状态筛选api",res);
}
//搜索框的搜索事件
const searchOrder_btn = async () => {
  if(searchInput.value.trim() === "") return;
  //发请求获取搜索的订单数据
  let res = await reqOrderListByOrderIdOrUsername(searchInput.value);
  if(res.code === 200) {
    //更新订单列表
    orderList.value = res.data.rows;
    orderCount.value = res.data.total;
    //信息提示
    ElMessage({type:"success",message:"订单搜索成功!"});
  } else {
    ElMessage({type:"error",message:"订单搜索失败!"});
  }
  console.log("根据下单用户名或订单号搜索订单信息api",res);
}
//订单信息表的select-all select事件
const tableSelectChange = (orderList:any) => {
  selectedOrderList.value = orderList.map(item => {
    return {
      orderId:item.orderId,
      orderState:item.orderState
    }
  })
}
//批量发货 批量删除订单 按钮事件
const batchUpdateOrderState_btn = async () => {
  //弹出messageBox提示
  ElMessageBox.confirm('确定要给这些订单发货吗?','提示',{confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning',}).then(async () => {
      //检查选择的每一项中是否包含 已支付和待发货 状态之外的
      selectedOrderList.value.forEach(item => {
        if(!(item.orderState.includes("已支付") || item.orderState.includes("待发货"))){
          return ElMessage({type:"warning",message:"选择的订单中包含已支付、待发货状态之外的!"});
        }
      })
      //发送请求批量更新订单状态-->发货
      let orderIds = selectedOrderList.value.map(item => item.orderId);
      let orderState = "已发货";
      let res = await reqBatchUpdateOrderState(orderIds, orderState);
      if(res.code === 200) {
        //批量修改订单状态成功
        //提示信息
        ElMessage({type:"success",message:"批量发货成功!"});
        //更新数据列表
        getOrderList(pagination_page.value, pagination_size.value);
        //置空选择的订单列表
        selectedOrderList.value = [];
      } else {
        //批量修改订单状态失败
        ElMessage({type:"error",message:res.msg});
      }
      console.log('批量修改订单状态api',res);
    }).catch(() => {
      ElMessage({type: 'info',message: '取消发货!'});
  })
}
const batchDeleteOrder_btn = async () => {
  //弹出messageBox提示
  ElMessageBox.confirm('确定要删除这些订单吗?','提示',{confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning',}).then(async () => {
      let orderIds = selectedOrderList.value.map(item => item.orderId);
      //发送请求
      let res = await reqBatchDeleteOrder(orderIds);
      if(res.code === 200) {
        //删除成功
        //提示信息
        ElMessage({type:"success",message:"批量删除订单成功!"});
        //更新数据列表
        getOrderList(pagination_page.value, pagination_size.value);
        //置空选择的订单列表
        selectedOrderList.value = [];
      } else {
        //删除失败
        ElMessage({type:"error",message:res.msg});
      }
      console.log('批量删除平台订单api',res);
    }).catch(() => {
      ElMessage({type: 'info',message: '取消批量删除订单!'})
  })
}

//drawer_dialog关闭前的回调
const drawerDialogHandleClose = () => {
  //关闭drawer_dialog
  drawer_dialog.value = false;
  //置空orderInfo_form
  orderInfo_form.id = 0;
  orderInfo_form.orderId = "";
  orderInfo_form.username = "";
  orderInfo_form.commodityName = "";
  orderInfo_form.commodityStandardStr = "";
  orderInfo_form.commodityCount = "";
  orderInfo_form.orderTotalPrice = "";
  orderInfo_form.orderState = "";
  orderInfo_form.linkUser = "";
  orderInfo_form.linkPhone = "";
  orderInfo_form.linkAddress = "";
  orderInfo_form.logisticsInfo = "";
  orderInfo_form.orderRemark = "";
  orderInfo_form.createTime = "";
  orderInfo_form.updateTime = "";
}
//drawer_dialog取消按钮
const drawerDialogCancel_btn = () => {
  drawerDialogHandleClose();
}
//drawer_dialog的提交修改按钮
const drawerDialogSave_btn = async () => {
  //对drawer_dialog对象数据进行简单校验
  if(orderInfo_form.orderId === "" && orderInfo_form.orderId === undefined) return;
  drawer_dialog_btn_loading.value = true;
  //校验成功，发请求更新订单信息
  let res = await updateOrderInfo(orderInfo_form);
  if(res.code === 200){
    ElMessage({type:"success",message:"订单修改成功!"});
    //关闭drawer_dialog
    drawerDialogHandleClose();
    drawer_dialog_btn_loading.value = false;  //loading效果关闭
    //重新请求订单列表数据
    getOrderList(pagination_page.value, pagination_size.value);
  } else {
    ElMessage({type:"error",message:"订单修改失败,请检查参数!"});
    drawer_dialog_btn_loading.value = false;  //loading效果关闭
  }
  console.log("平台订单修改api",res);
}

//生命周期
onMounted(() => {
  //获取订单列表数据
  getOrderList();
})
</script>

<style lang='scss' scoped>
.order-page{
  width: 100%;

  .page-header{
    width: 100%;

    .header-content-fun{
      width: 100%;
      margin-bottom: 20px;
      display: flex;
      justify-content: space-between;
      
      .header-dateSelect{
        width: 570px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .dateSelect-tip{
          margin-right: 10px;
        }
        .dateSelect-btn{
          margin-left: 20px;
        }
      }
    }

    .header-content-other{
      margin-bottom: 20px;
      display: flex;

      .other-search{
        width: 300px;
        margin-right: 30px;
        display: flex;
        justify-content: space-between;
      }
      .other-select{
        width: 270px;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }
  }
  // drawer_dialog抽屉buf
  .drawerDialog{
    .drawerDialog_content{
      .textarea{
        width: 320px;
        height: 50px;
        border-radius: 5px;
        border:1px solid #dcdfe6;
      }
    }
  }
  .page-pagination{
    margin: 40px 0;
  }
}
</style>